package com.zhongzhi.nn.push.util;

import com.zhongzhi.nn.push.model.LandInfo;
import com.zhongzhi.nn.push.model.NoticeInfo;
import com.zhongzhi.nn.push.model.ProjectInfo;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import sun.misc.BASE64Decoder;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 南宁接口推送工具类
 */
public class PushNNUtils {


    /**
     * 拼接 webService xml 文件
     * @param xml  参数  method 调用方法
     * @return
     */
    public static String getWebServiceXml(String xml,String method){

        StringBuilder soapData = new StringBuilder();
        soapData.append("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:epo=\"epoint\">\r\n");
        soapData.append("<soap:Header/>\r\n");
        soapData.append("<soap:Body>\r\n");
        soapData.append("<epo:" + method + ">\r\n");
        soapData.append("<epo:xml><![CDATA["+xml+"]]></epo:xml>\r\n");
        soapData.append(" </epo:" + method +">\r\n");
        soapData.append("</soap:Body>\r\n");
        soapData.append("</soap:Envelope>\r\n");
        String soapXml = soapData.toString();
        return soapXml;
    }

    //推送数据
    public static String sendForWebService(String requestUrl,String paramStr){

        StringRequestEntity requestEntity = null;
        try{
            requestEntity = new StringRequestEntity(paramStr,"text/xml","UTF-8");

        }catch (Exception e){
            e.printStackTrace();
        }

        PostMethod postMethod =new PostMethod(requestUrl);
        postMethod.setRequestEntity(requestEntity);

        HttpClient httpClient = new HttpClient();
        //发送请求，并获取响应对象
        int  statusCode = -1;
        try{
            statusCode =httpClient.executeMethod(postMethod);
        }catch (HttpException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(statusCode != HttpStatus.SC_OK){
            return null;
        }
        String resultJson = "";
        try {
            InputStream io = postMethod.getResponseBodyAsStream();
            resultJson=getMesage(io);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return resultJson;
    }

    /**
     * 处理返回结果
     * @param
     * @param result
     * @return
     */
    public static String getMesage(InputStream result) {
        BufferedReader br = new BufferedReader(new InputStreamReader(
                result));

        String str;
        StringBuffer resultJson=new StringBuffer();
        try {
            if (((str=br.readLine())!=null)) {
                resultJson.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return  null;
        }

        return resultJson.toString();
    }


    /**
     * 拼接项目参数
     * @param project
     * @param lands
     * @return
     */
    public static String getProjectResultXml(ProjectInfo project, List<LandInfo> lands){
        StringBuffer buffer = new StringBuffer();
        buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n");
        buffer.append("<xmlroot>\r\n");
        buffer.append("<recordSet table=\"TDJY_GongChengInfo\" pk=\"ProjectGuid\">\r\n");
        buffer.append("<record>\r\n");
        buffer.append("<ProjectBH>"+project.getProjectNo()+"</ProjectBH>\r\n");
        buffer.append("<ProjectGuid>"+project.getProjectGuid()+"</ProjectGuid>\r\n");
        buffer.append("<ProjectName>"+project.getProjectName()+"</ProjectName>\r\n");
        buffer.append("<FaBuXiaQuCode>"+project.getFbXzq()+"</FaBuXiaQuCode>\r\n");
        buffer.append("<ChangDiXiaQuCode>"+project.getKbXzq()+"</ChangDiXiaQuCode>\r\n");
        buffer.append("<OperateDate>"+project.getOperateDate()+"</OperateDate>\r\n");
        buffer.append("<OperateUserName>"+project.getOperateUserName()+"</OperateUserName>\r\n");

        for (LandInfo land: lands) {
            buffer.append("<bdlist>\r\n");
            buffer.append("<DiKuaiBianHao>"+land.getLandCode()+"</DiKuaiBianHao>\r\n");
            buffer.append("<DiKuaiGuid>"+land.getLandGuid()+"</DiKuaiGuid>\r\n");
            buffer.append("<DiKuaiWeiZhi>"+land.getLandAddress()+"</DiKuaiWeiZhi>\r\n");
            buffer.append("<GuaPaiJiaGe>"+land.getPrice()+"</GuaPaiJiaGe>\r\n");
            buffer.append("<JiaJiaFuDu>"+land.getAddPrice()+"</JiaJiaFuDu>\r\n");
            buffer.append("<DiKuaiYongTu>"+land.getLandUse()+"</DiKuaiYongTu>\r\n");
            buffer.append(" <DiKuaiMianJi>"+land.getLandArea()+"</DiKuaiMianJi>\r\n");
            buffer.append("<ChuRangNianXian>"+land.getTransferYear()+"</ChuRangNianXian>\r\n");
            buffer.append("<InvestProjectCode/>");
            buffer.append("<ReMark/>\r\n");
            buffer.append("</bdlist>\r\n");
        }

        buffer.append("</record>\r\n");
        buffer.append("</recordSet>\r\n");
        buffer.append("</xmlroot>\r\n");
        return buffer.toString();
    }

    /**
     * 拼接公告
     * @param noticeInfo
     * @param landInfos
     * @return
     */
    public static String getNoticeResultXml(NoticeInfo noticeInfo, List<LandInfo> landInfos) throws UnsupportedEncodingException {
        StringBuffer buffer = new StringBuffer();
        //日期格式化
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String bmStartTime = format.format(noticeInfo.getBmStartTime());
        String bmOverTime = format.format(noticeInfo.getBmOverTime());
        String gpStartTime = format.format(noticeInfo.getGpStartTime());
        String gpOverTime = format.format(noticeInfo.getGpOverTime());

        //在公告内容添加图片超链接
        String url = getImgAddress(landInfos);
        String content = PushNNUtils.encode(noticeInfo.getContent()+url);

        buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n");
        buffer.append("<xmlroot>\r\n");
        buffer.append("<recordSet table=\"tdjy_jiaoyigonggao\" pk=\" GongGaoGuid\">\r\n");
        buffer.append("<record>\r\n");
        buffer.append("<GongGaoGuid>"+noticeInfo.getNoticeGuid()+"</GongGaoGuid>\r\n");
        buffer.append("<ProjectBH>"+noticeInfo.getProjectNo()+"</ProjectBH>\r\n");
        buffer.append("<ProjectName>"+noticeInfo.getProjectName()+"</ProjectName>\r\n");
        buffer.append("<ProjectGuid>"+noticeInfo.getProjectGuid()+"</ProjectGuid>\r\n");
        buffer.append("<BaoMingStartDate>"+bmStartTime+"</BaoMingStartDate>\r\n");
        buffer.append("<BaoMingEndDate>"+bmOverTime+"</BaoMingEndDate>\r\n");
        buffer.append("<BaoJiaStartDate_Long>"+gpStartTime+"</BaoJiaStartDate_Long>\r\n");
        buffer.append("<BaoJiaEndDate_Long>"+gpOverTime+"</BaoJiaEndDate_Long>\r\n");
        buffer.append("<GongGaoTitle>"+noticeInfo.getGgTitle()+"</GongGaoTitle>\r\n");
        buffer.append("<GongGaoContent>"+content+"</GongGaoContent>\r\n");
        buffer.append("<OperateDate>"+noticeInfo.getOperateDate()+"</OperateDate>\r\n");
        buffer.append("<OperateUserName>"+noticeInfo.getOperateUserName()+"</OperateUserName>\r\n");

        for (LandInfo landInfo:landInfos){
            buffer.append("<bdlist>\r\n");
            buffer.append("<DiKuaiBianHao>"+landInfo.getLandCode()+"</DiKuaiBianHao>\r\n");
            buffer.append("<DiKuaiGuid>"+landInfo.getLandGuid()+"</DiKuaiGuid>\r\n");
            buffer.append("</bdlist>\r\n");
        }
        buffer.append("</record>\r\n");
        buffer.append("</recordSet>\r\n");
        buffer.append("</xmlroot>\r\n");
        return buffer.toString();
    }

    /**
     * 拼接变更公告
     * @param noticeInfo
     * @param landInfos
     * @return
     */
    public static String getChangeNoticeResultXml(NoticeInfo noticeInfo,List<LandInfo> landInfos) throws UnsupportedEncodingException {
        StringBuffer buffer = new StringBuffer();
        //日期格式化
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ggStartTime = format.format(noticeInfo.getGgStartTime());
        String ggOverTime = format.format(noticeInfo.getGgOverTime());

        //在公告内容添加图片超链接
        String url = getImgAddress(landInfos);
        String content = PushNNUtils.encode(noticeInfo.getContent()+url);

        buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n");
        buffer.append("<xmlroot>\r\n");
        buffer.append("<recordSet table=\"TDJY_ChengQingGongGao\" pk=\" GongGaoGuid\">\r\n");
        buffer.append("<record>\r\n");
        buffer.append("<GongGaoTitle>"+noticeInfo.getGgTitle()+"</GongGaoTitle>\r\n");
        buffer.append("<GongGaoGuid>"+noticeInfo.getNoticeGuid()+"</GongGaoGuid>\r\n");
        buffer.append("<ProjectBH>"+noticeInfo.getProjectNo()+"</ProjectBH>\r\n");
        buffer.append("<ProjectGuid>"+noticeInfo.getProjectGuid()+"</ProjectGuid>\r\n");
        buffer.append("<ProjectName>"+noticeInfo.getProjectName()+"</ProjectName>\r\n");
        buffer.append("<BaoMingStartDate>"+ggStartTime+"</BaoMingStartDate>\r\n");
        buffer.append("<BaoMingEndDate>"+ggOverTime+"</BaoMingEndDate>\r\n");
        buffer.append("<GongGaoContent>"+content+"</GongGaoContent>\r\n");
        buffer.append("<OperateDate>"+noticeInfo.getOperateDate()+"</OperateDate>\r\n");
        buffer.append("<OperateUserName>"+noticeInfo.getOperateUserName()+"</OperateUserName>\r\n");
        for (LandInfo landInfo:landInfos){
            buffer.append("<bdlist>\r\n");
            buffer.append("<DiKuaiBianHao>"+landInfo.getLandCode()+"</DiKuaiBianHao>\r\n");
            buffer.append("<DiKuaiGuid>"+landInfo.getLandGuid()+"</DiKuaiGuid>\r\n");
            buffer.append("</bdlist>\r\n");
        }
        buffer.append("</record>\r\n");
        buffer.append("</recordSet>\r\n");
        buffer.append("</xmlroot>\r\n");
        return buffer.toString();
    }


    /**
     * 拼接中标公告参数
     * @param noticeInfo
     * @param landInfos
     * @return
     */
    public static String getZBNoticeResultXml(NoticeInfo noticeInfo,List<LandInfo> landInfos) throws UnsupportedEncodingException {

        StringBuffer buffer = new StringBuffer();
        //日期格式化
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ggStartTime = format.format(noticeInfo.getGgStartTime());
        String ggOverTime = format.format(noticeInfo.getGgOverTime());

        //在公告内容添加图片超链接
        String url = getImgAddress(landInfos);
        String content = PushNNUtils.encode(noticeInfo.getContent()+url);

        buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n");
        buffer.append("<xmlroot>\r\n");
        buffer.append("<recordSet table=\"TDJY_ZhongBiaoGG\" pk=\"RowGuid\">\r\n");
        buffer.append("<record>\r\n");
        buffer.append("<ProjectBH>"+noticeInfo.getProjectNo()+"</ProjectBH>\r\n");
        buffer.append("<GongGaoGuid>"+noticeInfo.getNoticeGuid()+"</GongGaoGuid>\r\n");
        buffer.append("<ProjectName>"+noticeInfo.getProjectName()+"</ProjectName>\r\n");
        buffer.append("<ProjectGuid>"+noticeInfo.getProjectGuid()+"</ProjectGuid>\r\n");
        buffer.append("<BaoMingStartDate>"+ggStartTime+"</BaoMingStartDate>\r\n");
        buffer.append("<BaoMingEndDate>"+ggOverTime+"</BaoMingEndDate>\r\n");
        buffer.append("<GongGaoContent>"+content+"</GongGaoContent>\r\n");
        buffer.append("<OperateDate>"+noticeInfo.getOperateDate()+"</OperateDate>\r\n");
        buffer.append("<OperateUserName>"+noticeInfo.getOperateUserName()+"</OperateUserName>\r\n");

        for (LandInfo landInfo:landInfos){
            buffer.append("<bdlist>\r\n");
            buffer.append("<DiKuaiBianHao>"+landInfo.getLandCode()+"</DiKuaiBianHao>\r\n");
            buffer.append("<DiKuaiGuid>"+landInfo.getLandGuid()+"</DiKuaiGuid>\r\n");
            buffer.append("<ZhongBiaoPrice>"+landInfo.getCjPrice()+"</ZhongBiaoPrice>\r\n");
            buffer.append("<ZhongBiaoDW>"+landInfo.getCjDw()+"</ZhongBiaoDW>\r\n");
            buffer.append("</bdlist>\r\n");
        }
        buffer.append("</record>\r\n");
        buffer.append("</recordSet>\r\n");
        buffer.append("</xmlroot>\r\n");
        return buffer.toString();
    }

    /**
     * 给字符串加密
     * @param text
     * @return
     */
    public static String encode(String text) throws UnsupportedEncodingException {
        byte[] bytes = text.getBytes("UTF-8");
        String str = new sun.misc.BASE64Encoder().encode(bytes);
        return str;
    }


    /**
     * 解析xml字符串获取返回值
     * @param xml
     */
    public static String getXmlAttribute(String xml){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource((new StringReader(xml))));
            NodeList list = doc.getElementsByTagName("SetTDInfoResult");
            Node book = list.item(0);
            return book.getFirstChild().getNodeValue();
        } catch (Exception e) {
            e.printStackTrace();
            return  null;
        }


    }

    public static String getImgAddress(List<LandInfo> landInfos){
        StringBuffer buffer = new StringBuffer();

        String[] urls = new String[landInfos.size()];
        for (int i =0;i<landInfos.size();i++) {
            urls[i] = landInfos.get(i).getLandGuid();
           buffer.append( "  <a href="+urls[i]+" style=\"font-size: 20px;\" >"+landInfos.get(i).getLandCode()+"号宗地位置示意图地址，请点击该段文字跳转。（位置示意图仅供参考）</a>\r\n");
        }

        return buffer.toString();
    }


}
